package com.the_ring.chapter11;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.the_ring.chapter11.widget.ImageMattingView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import kotlin.jvm.internal.Ref;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    Toolbar headTl;
    ImageMattingView pictureIv;
    ActivityResultLauncher<Intent> launcher;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        headTl = findViewById(R.id.tl_head);
        setSupportActionBar(headTl);
        headTl.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        pictureIv = findViewById(R.id.iv_picture);
        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            Intent data = result.getData();
            if (data != null) {
                Uri uri = data.getData();
                Log.i(TAG, uri.toString());
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                    pictureIv.setBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.head, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.open_picture) {
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            launcher.launch(intent);
        } else if (id == R.id.save_picture) {
            Bitmap bitmap = pictureIv.getBitmap();
            if (bitmap != null) {
                // String path = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString();
                String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
                String time = new SimpleDateFormat("yyyyMMddHHmmss_SSSS").format(new Date());
                String newPath = path + "/" + time + ".png";
                Log.i(TAG, "Picture save path: " + path);
                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(newPath);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(this, "图片保存失败！！" + e.getMessage(), Toast.LENGTH_SHORT).show();
                } finally {
                    if (outputStream != null) {
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
                File file = new File(newPath);
                if (file.exists()) {
                    Toast.makeText(this, "图片保存成功，保存在 " + newPath, Toast.LENGTH_SHORT).show();
                }
            }
        }
        return super.onOptionsItemSelected(item);
    }
}